﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Logging;

namespace StyleMVVM.Utilities
{
	public class GlobalCache : IGlobalCache
	{
		private static string supplemental = typeof(GlobalCache).FullName;

		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(GlobalCache)).As(typeof(IGlobalCache)).AndShared();
		}

		public void AddWithAbsoluteExpireTime(string key, object value, DateTimeOffset absoluteExpire)
		{
			MemoryCache.Default.Add(key, value, absoluteExpire);
		}

		public void AddWithSlidingExpireTime(string key, object value, TimeSpan absoluteExpire)
		{
			MemoryCache.Default.Add(key, value, new CacheItemPolicy() { SlidingExpiration = absoluteExpire });
		}

		public void RemoveFromCache(string key)
		{
			MemoryCache.Default.Remove(key);
		}

		public object GetValue(string key)
		{
			try
			{
				return MemoryCache.Default.Get(key);
			}
			catch (Exception exp)
			{
				Logger.Info("MemoryCache threw exception while calling get for key: " + key, supplemental);
			}

			return null;
		}
	}
}